package com.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.security.dao.UserDao;
import com.security.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * @作者: 林江
 * @创建时间: 2023/12/30
 * @功能:
 */
@Service
public class LoginUserDetailsService implements UserDetailsService {

    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (username.matches("\\d{11}")) {
            wrapper.eq(SysUser::getPhone, username);
        } else {
            wrapper.eq(SysUser::getUsername, username);
        }
        SysUser sysUser = userDao.selectOne(wrapper);
        return buildUser(sysUser);
    }

    private UserDetails buildUser(SysUser sysUser) {
        String pwd = new StringBuilder("{")
                .append(sysUser.getEncrypt()).append("}")
                .append(sysUser.getPassword()).toString();

        User user = new User(sysUser.getUsername(), pwd, Collections.singleton(new SimpleGrantedAuthority("ROLE_ADMIN")));

        return user;
    }
}
